

var mariadb = require('mariadb');
const dbPool = mariadb.createPool({
	database: "cyue_share",
	user:'root', 
	password: 'weifei'
})


BigInt.prototype.toJSON = function () { return this.toString() };


module.exports = {

	/**
	 * @returns { mariadb.Pool }
	 */
	getPool() {
		return dbPool;
	},


	/**
	 * 
	 * @param { string | mariadb.QueryOptions } sql 
	 * @param { any[] } values 
	 * @returns { Promise<any[] | Object> }
	 */
	query(sql, values)
	{
		if (!values)
			return dbPool.query(sql);
		return dbPool.query(sql, values);
	},


	/**
	 * @returns { Promise<mariadb.Connection> }
	 */
	createConnection() {
		return mariadb.createConnection({
			database: "cyue_share",
			user: "weifei",
			password: 'weifei'
		})
	},


	/**
	 * @returns { Promise<PoolConnection> }
	 */
	getConnection() {
		return dbPool.getConnection();
	},


	/**
	 * 
	 * @param { string[] } sqlArray
	 * @param { any[][] } paramArray
	 * @returns { Promise<any[][]> }
	 */
	transactionQuery(sqlArray, paramArray)
	{
		return new Promise((resolve, reject) => {
			dbPool.getConnection()
			.then(connection => {
				connection.beginTransaction()
				.then(() => {
	
					const promiseArray = new Array(sqlArray.length);
					for (let i = 0; i < sqlArray.length; i++) {
						const sql = sqlArray[i];
						const param = paramArray[i];

						promiseArray[i] = new Promise((resolve, reject) => {
							connection.query(sql, param)
							.then(result => {
								resolve(result);
							})
							.catch(err => {
								console.error(err);
								reject(err);
							});
						})
					}

					Promise.all(promiseArray)
					.then(resultArray => {
						connection.commit()
						.then(() => {
							connection.release();
							resolve(resultArray);
						})
						.catch(commitError => {
							console.error(commitError);
							connection.rollback()
							.then(() => {
								connection.release();
								reject(commitError);
							})
							.catch(() => {
								connection.release();
								reject(commitError);
							});
						});
					});
	
					
	
				})
				.catch(err => {
					console.error(err);
					connection.release();
					reject(err);
				});
	
			})
			.catch(err => {
				console.error(err);
				reject(err);
			});
		});
		
	}
}




